package KK
{
	import KK.Cache.CacheManager;
	import KK.Controls.Button.TextButton;
	import KK.EMVC.Control.Control;
	import KK.Event.GameSystemEvent;
	import KK.GameBase.IMessageQueue;
	import KK.GameBase.MSGEvent;
	import KK.System.ApplicationManager;
	import KK.System.IO.File;
	import KK.System.IO.FileEvent;
	import KK.System.System;
	import KK.net.ResourceManager;
	
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.FileFilter;
	import flash.utils.ByteArray;
	
	public class MainHandler extends Control
	{
		private static const UI_BUTTON:String="button";
		private var imprinter:Imprinter;
		public function MainHandler()
		{
			//TODO: implement function
			super();
			init();
		}
		
		private function init():void{
			
			imprinter=new Imprinter();
			addChild(imprinter);
			imprinter.y+=imprinter.height;
		}
		
		/**
		 * 
		 * @param _event
		 * 
		 */
		override public function BindEvent(_event:IMessageQueue):Boolean{
			var result:Boolean=super.BindEvent(_event);
			initEvent();
			return result;
		}
		
		/**
		 * 初始化事件 
		 * 
		 */
		private function initEvent():void{
			AttentionMessage(GameSystemEvent.RESOURCE_LOADED,ResourceLoaded);
		}
		
		/**
		 * 资源加载  
		 * @param event
		 * 
		 */
		private function ResourceLoaded(event:MSGEvent):void{
			addButton();
		}
		
		/**
		 * 添加按钮  
		 * 
		 */
		private function addButton():void{
			//ResourceManager.AddSwfLoader("assets/UI.swf",ButtonLoaded);
			var save:TextButton=new TextButton();
			var open:TextButton=new TextButton();
			
			save.addEventListener(MouseEvent.CLICK,onSave);
			
			open.addEventListener(MouseEvent.CLICK,onOpen);
			
			
			
			save.Skin=CacheManager.GetCache(UI_BUTTON).bitmapData;
			open.Skin=CacheManager.GetCache(UI_BUTTON).bitmapData;
			
			addChild(save);
			addChild(open);
			
			Global.addClipTip(save,"保存地图 ");
			Global.addClipTip(open,"打开地图 ");
			
			
			save.Label="save";
			open.Label="open"; 
			save.x=open.width+5;
		} 
		
		
		/**
		 * 添加 按钮响应  
		 * @param event
		 * 
		 */
		private function onSave(event:Event):void{ 
			
			var byte:ByteArray=new ByteArray();
			imprinter.getBytes(byte);
			LogInfo(System.ByteToHEX(byte));
			File.Save(byte);
		}
		
		/**
		 * 打开文件  
		 * @param event
		 * 
		 */
		private function onOpen(event:Event):void{
			
			File.Open([new FileFilter("map","*.dat")]);
			File.Instance.addEventListener(FileEvent.FILE_LOADED,Loaded);
		}
		
		/**
		 * 数据读取完毕  
		 * @param event
		 * 
		 */
		private function Loaded(event:FileEvent):void{
			imprinter.setBytes(event.Data);
			
		}
		
		/**
		 * 添加影片 
		 * @param child
		 * 
		 */
		private function addChild(child:DisplayObjectContainer):void{
			Global.Word.addChild(child);
		}
	}
}